
<template>
	<view class="chat">
	<view style="height: var(--status-bar-height); background-color: #f5f5f5;"></view>
    <!-- 顶部标题 -->
    <view class="topTabbar">
      <!-- 返回图标 -->
      <u-icon class="icon" name="arrow-left" size="20px" color="#000" @click="goback()"></u-icon>
      <!-- 标题 -->
      <view class="text">{{state.username}}</view>
    </view>
		<view class="top">
			<view class="left">
				<image :src="state.info.show_image"></image>
				<view class="userNews">
					<view class="name">{{state.info.title}}</view>
					<view class="jg">￥{{state.info.maxprice}}</view>
				</view>
			</view>
			<view class="right" v-if="state.auth_type!='3'" @click="state.juShow=true">
				立即支付
			</view>
			<view class="right" v-else @click="state.show=true">
				修改金额
			</view>
		</view>
		<scroll-view  :style="{height:'calc('+`${windowHeight()-inputHeight() - state.h}rpx`+' - var(--status-bar-height))'}"
		id="scrollview"
		scroll-y="true" 
		:scroll-top="state.scrollTop"
		class="scroll-view"
		>
			<!-- 聊天主体 -->
			<view id="msglistview" class="chat-body">
				<!-- 聊天记录 -->
				<view v-for="(item,index) in state.list" :key="index" >
					<!-- 自己发的消息 -->
					<view class="item self" v-if="item.is_mine=='1'" >
						<!-- 文字内容 -->
						<view class="content right">
							{{setJs(item.content,'content')}}
						</view>
						<!-- 头像 -->
						<image class="avatar" :src="item.user.avatar"></image>
					</view>
					<!-- 机器人发的消息 -->
					<view class="item Ai" v-if="item.is_mine!='1'">
						<!-- 头像 -->     
						<image class="avatar" :src="item.user.avatar">
						</image>
						<!-- 文字内容 -->
						<view class="content left">
							{{setJs(item.content,'content')}}
						</view>
					</view>
				</view>
			</view>
		</scroll-view>
		<!-- 底部消息发送栏 -->
		<!-- 用来占位，防止聊天消息被发送框遮挡 -->
		<view class="chat-bottom" :style="{height: `${inputHeight()}rpx`}">
			<view class="send-msg" :style="{bottom:`${state.keyboardHeight - 60}rpx`}">
				<view class="uni-textarea">
				 <!-- <textarea v-model="state.chatMsg"
					maxlength="300"
					confirm-type="send"
					@confirm="handleSend"
					placeholder="快来聊天吧~"
					:show-confirm-bar="false"
					:adjust-position="false"
					@linechange="sendHeight"
					@focus="focus" @blur="blur"
				   auto-height></textarea> -->
				   <input type="text" @focus="focus" @blur="blur" @confirm="handleSend" placeholder="快来聊天吧~" v-model="state.chatMsg"/>
				</view>
				<button @click="handleSend" class="send-btn">发送</button>
			</view>
		</view>
		
		<u-popup :show="state.show" :round="10" mode="bottom" @close="close">
			<view class="bottomBox">
				<view class="top">
					<view class="title">修改金额</view>
					<image src="../../static/icon.png" @click="state.show=false"></image>
				</view>
				<view class="dinr">
					<view class="inputbox">
						<text>￥</text>
						<input type="number" placeholder="请输入金额" v-model="state.jenumber"/>
					</view>
					<view class="bc" @click="open">保存</view>
				</view>
			</view>
		</u-popup>
		<!-- 支付-->
		<view class="tan" v-if="state.juShow">
			<view class="bgcen">
				<view class="times">
					购买解锁次数           
				</view>
				<view class="cha" @click="state.juShow=false">
					<image src="../../static/icon.png" mode="" ></image>
				</view>
				<view class="qian">
					<text>￥</text>{{state.info.maxprice}}
				</view>
				<view class="buc">
					付款说明：
				</view>
				<view class="xuan">
					<view class="ones" v-for="(val,index) in state.juList" :key='index' @click="getXuan(val.id)">
						<view class="lezhi">
							<image :src="val.img" mode=""></image>{{val.name}}
						</view>
						<view class="dui">
							<image src="../../static/login_icon_select2@2x.png" mode="" v-if="val.id==state.juid"></image>
							<image src="../../static/icon_select@2x.png" mode="" v-else></image>
						</view>
					</view>
				</view>
				
				<view class="juBao" @click="isZf()">
					确认支付
				</view>
			</view>
		</view>
	</view>
</template>
<script setup>
	import {ref,onUpdated,reactive,computed,onMounted} from 'vue';
	import sheep from '@/sheep';
	import {onLoad,onUnload} from '@dcloudio/uni-app';
	import GoEasy from 'goeasy-lite';
	const state = reactive({
		show:false,
		jenumber:'',
		h:245,
		//键盘高度
		auth_type:'',
		keyboardHeight:30,
		//底部消息发送高度
		bottomHeight: 0,
		//滚动距离
		scrollTop: 0,
		
		//发送的消息
		chatMsg:"",
		
		channel:'',
		list:[],
		page:1,
		pageSize:10,
		hasMore:true,
		isLoad:false,
		
		msgList:[],
		// 我自己的用户信息
		isUserid:'',
		isUsername:'',
		isUserimg:'',
		
		userId:'',
		username:'',
		userimg:'',
		userJg:'',
		
		id:'',
		info:{},
		
		
		juList:[
			{
				id:1,
				name:'微信支付',
				img:'../../static/pay_icon_wei@2x.png'
			},
			{
				id:2,
				name:'支付宝支付',
				img:'../../static/pay_icon_zhi@2x.png'
			}
		],
		juid:1,
		authentication:'',
		juShow:false,
	})
	const goEasy = GoEasy.getInstance({
	  host:'hangzhou.goeasy.io', //新加坡host：singapore.goeasy.io
	  appkey: "BC-a927530bb2fc4414b95f9af7b9254b70", //替换为您的应用appkey
	  modules: ['pubsub']
	});
	onLoad((res)=>{
		if(res.userId){
			state.userId = res.userId
		}
		if(res.userimg){
			state.userimg = res.userimg
		}
		if(res.username){
			state.username = res.username
		}
		if(res.id){
			state.id = res.id
		}
		scrollToBottom();
		getUserInfo();
	})
	onUnload(res=>{
		goEasy.disconnect({
			onSuccess: function(){},
			onFailed: function(error){}
		});
	})
	
	function open(){
		addNews('setGoods',2)
		getxiu()
		state.show=false
	}
	// 修改价格
	async function getxiu(){
		const {code,data} = await sheep.$api.zqzApi.setprice({
				token:uni.getStorageSync('token'),
				user_id:state.userId,
				fabu_id:state.id,
				price:state.jenumber,
			})
			if(code=='1'){
				
			}
	}
	
	
	function close(){
		state.show=false
	}
	function getXuan(e){
		state.juid = e
	}
	// 支付
	async function isZf(){
		let pay_type = ''
		let method =''
		let codes=''
		let port = uni.getSystemInfoSync().uniPlatform
		if(port=='windows'){
			method = 'web'
		}
		if(port=='mp-weixin'){
			method = 'miniapp'
		}
		if(port=='app'){
			method = 'app'
		}
		if(state.juid='1'){
			pay_type = 'wechat'
		}else{
			pay_type = 'alipay'
		}
		if(port=='devtools'||port=='mp-weixin'){
			method = 'miniapp'
			// 微信小程序支付
			uni.login({
				"provider": "weixin",
				"onlyAuthorize": true, // 微信登录仅请求授权认证
				success: function(event){
					codes = event.code
					console.log(event.code,'三生世')
					getWei(pay_type,method,codes)
				},
				fail: function (err) {
			        // 登录授权失败  
			        // err.code是错误码
			    }
			})
		}else{
			const {code,data} = await sheep.$api.zqzApi.createOrder({
				token:uni.getStorageSync('token'),
				fabu_id:state.id,
				amount:state.info.maxprice,
				pay_type:pay_type,
				method:method
			})
		}
	}
	//微信小程序支付
	async function getWei(pay_type,method,codes){
		const {code,data} = await sheep.$api.zqzApi.createOrder({
			token:uni.getStorageSync('token'),
			fabu_id:state.id,
			amount:state.info.maxprice,
			pay_type:pay_type,
			method:method,
			code:codes
		})
		if (code == 1) {
			let orderInfo=data
		   uni.requestPayment({
		       provider: 'wxpay',    //支付类型-固定值
		       timeStamp:orderInfo.timeStamp, // 时间戳（单位：秒）
		       nonceStr: orderInfo.nonceStr, // 随机字符串
		       package: orderInfo.package, // 固定值
		       signType:orderInfo.signType, //固定值
		       paySign:orderInfo.paySign, //签名
		       success: function (res) {
					uni.showToast({
					  title: '支付成功',
					  icon: 'success',
					  duration: 2000
					})
					setTimeout(()=>{
						uni.navigateTo({
							url:"/pages/user/order?id=1&status=1"
						})
					},2000)
		       },
		       fail: function (err) {
		           console.log('fail:' + JSON.stringify(err));
		       }
		   });
		}
	}
	// 获取当前用户头像昵称
	async function getUserInfo(){
		
		const {code,data} = await sheep.$api.user.userInfo({
			token:uni.getStorageSync('token'),
		})
		
		if (code == 1) {
		   state.isUserid = data.id
		   state.isUserimg = data.avatar
		   state.isUsername = data.nickname
		   state.authentication=data.authentication
		   ljIm()
		}
	}
	
	function ljIm(){
		goEasy.connect({
			onSuccess: function () {
				getchatMsg()
			},
			onFailed: function (error) { //连接失败
				if(error.code=='408'){
					getchatMsg()
				}
			}
		});
	}
	function setJs(e,key){
		return JSON.parse(e)[key]
	}
	// im实时通讯部分
	async function getchatMsg(){
		const {code,data} = await sheep.$api.zqzApi.getChannel({
			token:uni.getStorageSync('token'),
			receive_user_id:state.userId,
			fabu_id:state.id,
		})
		if(code=='1'){
			state.channel = data.channel
			if(state.id==''){
				state.id = data.fabu_id
			}else{
				addNews('getGoods',2)
			}
			getGoods()
			getNews()
		}
	}
	async function getNews(){
		const {code,data} = await sheep.$api.zqzApi.getCon({
			token:uni.getStorageSync('token'),
			channel:state.channel,
			page:state.page,
			limit:state.pageSize,
		})
		if(code=='1'){
			let list = data
			let hasmore = list.length===state.pageSize
			list = state.list.concat(list)
			state.hasMore = hasmore
			state.list = list
			state.isLoad = false
			state.page = state.page+1
			getNewsd()
		}
	}
	function getNewsd(){
		goEasy.pubsub.subscribe({
			channel: state.channel,
			onMessage: function (message) {
				let data = JSON.parse(message.content)
				if(data.is_chat=='1'){
					let cont = JSON.stringify({type:data.type,content:data.content})
					let is_mine = '1'
					if(data.send_user_id == state.isUserid){
						is_mine='1'
					}else{
						is_mine='0'
					}
					state.list.push({
						is_chat:data.is_chat,
						content:cont,
						is_mine:is_mine,
						user:{
							avatar:data.user_info.avatar,
							nickname:data.user_info.nickname,
						}
					})
				}else{
					let nr = data.content.split(',')
					if(nr[0]=='getGoods'){
						state.id=nr[1]
						getGoods()
					}
					if(nr[0]=='setGoods'){
						state.info.maxprice = nr[1]
					}
					if(nr[0]=='idGoods'){
						addNews('getGoods',2)
					}
				}
			},
		})
	}
	async function getGoods(){
		let nr={}
		console.log(state.auth_type,'state.auth_type')
		if(state.authentication==3){
			console.log(33333)
			nr={
			    fabu_id:state.id,
				user_id:state.userId
			}
		}else{
			nr={
			    fabu_id:state.id,
				
			}
		}
		const {code,data} = await sheep.$api.zqzApi.info(nr)
		if(code=='1'){
			state.info = data
			if(state.isUserid==data.user_info.id){
				state.auth_type = 3
			}else{
				state.auth_type = ''
			}
		}
	}
	async function addNews(text,is){
		let nr = ''
		if(is=='2'){
			if(text=='getGoods'){
				let arr = [text,state.id]
				nr = arr.join(',')
			}
			if(text=='setGoods'){
				let arr = [text,state.jenumber]
				nr = arr.join(',')
			}
			if(text=='idGoods'){
				let arr = [text,'']
				nr = arr.join(',')
			}
		}else{
			nr = text
			if(text==''){
				return
			}
		}
		const {code,data} = await sheep.$api.zqzApi.addCon({
			token:uni.getStorageSync('token'),
			content:nr,
			receive_user_id:state.userId,
			type:'send',
			channel:state.channel,
			is_chat:is,
		})
		if(code=='1'){
			if(is=='1'){
				state.chatMsg=''
			}
			if(text=='setGoods'){
				state.jenumber=''
			}
		}
	}
	
	
	// 消息样式自适应代码
	function windowHeight() {
		    return rpxTopx(uni.getSystemInfoSync().windowHeight)
		}
	function inputHeight(){
			return state.bottomHeight+state.keyboardHeight
		}
	function goback() {
		uni.navigateBack({
			delta:1
		})
    }
	function focus(){
		scrollToBottom()
	}
	function blur(){
		scrollToBottom()
	}
	function rpxTopx(px){
		let deviceWidth = uni.getSystemInfoSync().windowWidth
		let rpx = ( 750 / deviceWidth ) * Number(px)
		return Math.floor(rpx)
	}
	function sendHeight(){
				setTimeout(()=>{
					let query = uni.createSelectorQuery();
					query.select('.send-msg').boundingClientRect()
					query.exec(res =>{
						state.bottomHeight = rpxTopx(res[0].height)
					})
				},10)
			}
	function scrollToBottom(e){
				setTimeout(()=>{
					let query = uni.createSelectorQuery().in(this);
					query.select('#scrollview').boundingClientRect();
					query.select('#msglistview').boundingClientRect();
					query.exec((res) =>{
						if(res[1].height > res[0].height){
							state.scrollTop = rpxTopx(res[1].height - res[0].height)
						}
					})
				},1000)
			}
	function handleSend() {
				//如果消息不为空
				if(!state.chatMsg||!/^\s+$/.test(state.chatMsg)){
					addNews(state.chatMsg,1)
				}else {
					
				}
			}
</script>
<style lang="scss" scoped>
	.tan{
		width:100%;
		height:100vh;
		position: fixed;
	    top:0;
		left:0;
		background: rgba(0,0,0,0.4);
		.bgcen{
			width: 100%;
			height: 700rpx;
			background: #fff;
			position:absolute;
			bottom:0;
			border-radius: 16rpx 16rpx 0 0;
			// position: relative;
			.qian{
				width: 100%;
				margin: 50rpx auto;
				text-align: center;
				font-size:48rpx;
				font-family: PingFang SC-Bold, PingFang SC;
				font-weight: bold;
				color: #333333;
				text{
					font-size: 28rpx;
					font-family: PingFang SC-Bold, PingFang SC;
					font-weight: bold;
					color: #333333;
				}
			}
			.xuan{
				width:calc(100% - 64rpx);
				margin: 20rpx auto;
				overflow:hidden;
			    
				.ones{
					width: 100%;
					line-height:80rpx;
					text-align:center;
					border-radius: 12rpx;
					margin: 20rpx 0;
					display:flex;
					align-items: center;
					justify-content:space-between;
					.lezhi{
						display:flex;
						align-items: center;
						image{
							 width: 48rpx;
							 height:48rpx;
							 margin-right:10rpx;
						}
					 }
					image{
						 width: 48rpx;
						 height:48rpx;
					}
				}
				.onesmo{
					width: 100%;
					line-height:80rpx;
					text-align:center;
					border-radius: 12rpx;
					margin: 20rpx 0;
				}
			}
			.buc{
				width:calc(100% - 64rpx);
				margin: 20rpx auto;
				font-size: 28rpx;
				color: #999999;
			}
			
			.juBao{
				width:calc(100% - 64rpx);
				margin:50rpx auto;
				background: #1BDDD0;
				color:#fff;
				border-radius: 54rpx;
				line-height: 92rpx;
				text-align: center;
			}
			.times{
				text-align: center;
				width: 100%;
				line-height: 80rpx;
				font-weight: bold;
				border-bottom: 1px solid #EFEFEF;
			}
			.cha{
				position: absolute;
				top:20rpx;
				right:20rpx;
				image{
					width: 40rpx;
					height:40rpx;
				}
			}
		}
	}
	
	page{background: #f5f5f5; position: absolute; width: 100%; height: 100%;}
	$chatContentbgc: #C2DCFF;
	$sendBtnbgc: #4F7DF5;
	
	view,button,text,input,textarea {
		margin: 0;
		padding: 0;
		box-sizing: border-box;
	}
 
	/* 聊天消息 */
	.chat {
		
     .topTabbar {
		  
          width: 100%;
          height: 90rpx;
          display: flex;
          justify-content: space-between;
		  align-items: center;
		  background-color: #f5f5f5;
          .icon {
            margin-left: 20rpx;
          }
      
          .text {
            margin: auto;
            font-size: 16px;
            font-weight: 700;
          }
      
          .button {
            width: 10%;
            margin: auto 20rpx auto 0rpx;
          }
        }
		.scroll-view {
			::-webkit-scrollbar {
					    display: none;
					    width: 0 !important;
					    height: 0 !important;
					    -webkit-appearance: none;
					    background: transparent;
					    color: transparent;
					  }
			
			// background-color: orange;
			background-color: #F6F6F6;
			
			.chat-body {
				display: flex;
				flex-direction: column;
				padding-top: 23rpx;
				// background-color:skyblue;
				
				.self {
					justify-content: flex-end;
				}
				.item {
					display: flex;
					padding: 23rpx 30rpx;
					// background-color: greenyellow;
 
					.right {
						background-color: $chatContentbgc;
					}
					.left {
						background-color: #FFFFFF;
					}
                    // 聊天消息的三角形
					.right::after {
						position: absolute;
						display: inline-block;
						content: '';
						width: 0;
						height: 0;
						left: 100%;
						top: 10px;
						border: 12rpx solid transparent;
						border-left: 12rpx solid $chatContentbgc;
					}
 
					.left::after {
						position: absolute;
						display: inline-block;
						content: '';
						width: 0;
						height: 0;
						top: 10px;
						right: 100%;
						border: 12rpx solid transparent;
						border-right: 12rpx solid #FFFFFF;
					}
 
					.content {
						position: relative;
						max-width: 486rpx;
						border-radius: 8rpx;
						word-wrap: break-word;
						padding: 24rpx 24rpx;
						margin: 0 24rpx;
						border-radius: 5px;
						font-size: 32rpx;
						font-family: PingFang SC;
						font-weight: 500;
						color: #333333;
						line-height: 42rpx;
					}
 
					.avatar {
						display: flex;
						justify-content: center;
						width: 78rpx;
						height: 78rpx;
						background: $sendBtnbgc;
						border-radius: 50rpx;
						overflow: hidden;
						
						image {
							align-self: center;
						}
 
					}
				}
			}
		}
 
		/* 底部聊天发送栏 */
		.chat-bottom {
			width: 100%;
			height: 100rpx;
			background: #F4F5F7;
			transition: all 0.1s ease;
			
			.send-msg {
				display: flex;
				align-items: flex-end;
				padding: 16rpx 30rpx;
				width: 100%;
				min-height: 177rpx;
				position: fixed;
				bottom: 0;
				background: #fff;
				transition: all 0.1s ease;
			}
 
			.uni-textarea {
				padding-bottom: 75rpx;  
				textarea {
					width: 537rpx;
					min-height: 75rpx;
					max-height: 500rpx;
					background: #f1f1f1;
					border-radius: 40rpx;
					font-size: 32rpx;
					font-family: PingFang SC;
					color: #333333;
					line-height: 74rpx;
					padding: 5rpx 8rpx;
					text-indent: 30rpx;
				}
			}
            
			.send-btn {
				display: flex;
				align-items: center;
				justify-content: center;
				margin-bottom: 76rpx;
				margin-left: 25rpx;
				width: 120rpx;
				height: 75rpx;
				background: #1BDDD0;
				border-radius: 50rpx;
				font-size: 28rpx;
				font-family: PingFang SC;
				font-weight: 500;
				color: #FFFFFF;
			}
		}
	}
	.top{width: 100%; height: 155rpx; padding-left: 32rpx; padding-right: 32rpx; border-bottom: 1rpx solid #E9E9E9; display: flex; align-items: center; justify-content: space-between;}
	.top .left{display: flex; align-items: center;}
	.top .left image{width:100rpx; height: 100rpx;}
	.top .left .userNews{margin-left: 10rpx; display: flex; flex-direction: column; justify-content: space-between; height: 80rpx; font-size: 28rpx;}
	.top .left .userNews .jg{color:#F33737; font-weight: bold;}
	.top .right{width: 150rpx; height: 60rpx; display: flex; align-items: center; justify-content: center; color:#fff; background:#1BDDD0; font-size: 28rpx; border-radius:32rpx;}
	.bottomBox{width: 100%; height:500rpx;}
	.bottomBox .top{width: 100%; height: 100rpx;font-size: 32rpx; position: relative; color: #333; font-weight: bold; border-bottom: 1rpx solid #efefef; display: flex; align-items: center; justify-content: center;}
	.bottomBox .top image{width: 48rpx; height: 48rpx; position: absolute; right: 32rpx;}
	.bottomBox .dinr{width: 100%; height: 400rpx; display: flex; align-items: center; justify-content: center; flex-direction: column;}
	.bottomBox .dinr .inputbox{width: calc(100% - 64rpx); height: 100rpx; border-radius: 24rpx; border:1rpx solid #efefef; display: flex; display: flex; align-items: center; justify-content: center;}
	.bottomBox .dinr .inputbox text{margin-left: 20rpx;}
	.bottomBox .dinr .inputbox input{width: calc(100% - 95rpx); margin-left: 15rpx;}
	.bottomBox .dinr .bc{width: calc(100% - 64rpx); height:90rpx; border-radius: 54rpx; background: #1BDDD0; color: #fff; display: flex; align-items: center; justify-content: center; font-size: 32rpx; margin-top: 60rpx;}
	.uni-textarea input{width: 530rpx; height: 75rpx; background: #f1f1f1; border-radius: 40rpx; padding-left: 20rpx; padding-right: 20rpx;}
</style>